
import React from 'react';
import { inject, observer } from 'mobx-react';
import {WeaDialog,WeaRightMenu,WeaNewScroll,WeaFormItem,WeaSearchGroup,WeaLocaleProvider,WeaTools} from "ecCom"
import {Button,Modal,message} from "antd"
import {WeaTableNew,WeaSwitch} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
import {toJS} from "mobx"
import equal from 'deep-equal'
import ProjectCondition from '../list/projectCondition'
import * as Prj_Apis from '../../apis/project'
import ProjectLogDialog from "./modifyLogDialog"
import ProjectFieldLogDialog from './projectFieldLogDialog';
import ProjectFieldDetailLogDialog from './ProjectFieldDetailLogDialog';
import SaveTemplateDialog from "../dialog/SaveTemplateDialog";

@observer
export default class ProjectDialog extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            workPlanVisible: false
        }
    }

    componentDidMount() {
        const { contentStore } = this.props;
        if (!window.weaWorkplan) {
            // 异步加载别模块的静态资源
            eventRegister.loadModule('f_workplan', () => {
                contentStore.setLoaded(true)
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
            })
        } else {
            contentStore.setLoaded(true)
        }
    }

    componentWillReceiveProps(nextProps) {
        let keyOld = "";
        let keyNew = "";
        if( this.props.location && nextProps.location && this.props.location.query && nextProps.location.query){
            keyOld = this.props.location.query.prjid;
            keyNew = nextProps.location.query.prjid;
        }else{
            keyOld = this.props.prjid;
            keyNew = nextProps.prjid;
        }
        //点击菜单路由刷新组件
        if (keyOld !== keyNew) {
            const { contentStore } = nextProps;
            if (!window.weaWorkplan) {
                // 异步加载别模块的静态资源
                eventRegister.loadModule('f_workplan', () => {
                    contentStore.setLoaded(true)
                }, () => {
                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                })
            } else {
                contentStore.setLoaded(true)
            }
        }
    }

    render(){
        let _this = this;
        const {contentStore} = this.props;
        const {visible,handleDialog,prjInfo,prjForm,setFormFields,setValidate,prjLogTableStore, prjFieldLogTableStore, prjFieldDetailLogTableStore, fieldname, prjid} = contentStore;
        const title = getLabel(83808,"编辑项目");
        const account = WeaTools.ls.getJSONObj('theme-account');
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@zdlktp`}  
                title={title  }
                visible={visible}
                buttons={this.getBottomButtons()}
                icon="icon-coms-project"
                iconBgcolor="#217346"
                onCancel={()=>{handleDialog(false)}}
                style={{width:1000,height:700}}>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@jmhbrz`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}  >
                    <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@1lj6ex`} height={"100%"}>
                        <ProjectCondition ecId={`${this && this.props && this.props.ecId || ''}_ProjectCondition@j88ph3`} fieldInfo={prjInfo} form={prjForm} setFormFields={(v)=>{setFormFields(v)}} setValidate={(v)=>{setValidate(v)}} />
                        <ProjectLogDialog ecId={`${this && this.props && this.props.ecId || ''}_ProjectLogDialog@ej3b1r`} ref="projectLogDialog" title={getLabel('33782','项目日志') } tableStore={prjLogTableStore} store={contentStore} />
                        <ProjectFieldLogDialog ecId={`${this && this.props && this.props.ecId || ''}_ProjectFieldLogDialog@l0zxlg`} title={getLabel('82274','字段日志') } tableStore={prjFieldLogTableStore} store={contentStore} />
                        <ProjectFieldDetailLogDialog ecId={`${this && this.props && this.props.ecId || ''}_ProjectFieldDetailLogDialog@3u0cbi`} title={getLabel('82274','字段日志')+"-"+fieldname } tableStore={prjFieldDetailLogTableStore} store={contentStore} />
                        <SaveTemplateDialog ecId={`${this && this.props && this.props.ecId || ''}_SaveTemplateDialog@audzl0`} prjCardStore={contentStore}/>
                        {
                            contentStore.isreload&&window.weaWorkplan && window.weaWorkplan.com && window.weaWorkplan.com.WorkPlanCreate &&
                            (<window.weaWorkplan.com.WorkPlanCreate ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@69wd75`}
                                type={"create"}//新建为'create',查看为'preview',编辑edit,共享share
                                visible={_this.state.workPlanVisible}//显隐受控
                                doClose={() => { _this.setWorkPlanVisible(false); }}//关闭回调
                                onlyClose={() => { _this.setWorkPlanVisible(false) }}//关闭回调,只做关闭操作
                                workPlanId={""} //日程id，1查看日程时用到
                                createConditionParams={[]}//创建的默认值日期和时间,没有传[]
                                activeKey={""} //查看页面显示的面板1是基本信息，7是相关交流
                                //{(key) => { }}//查看页面切换面板的回调
                                selectUser={account && account.userid}//新建日程的创建人id
                                workPlanTypeOptions={"2"}//客户模块的新建日程，普通新建传'',客户新建传3
                                crmIDs={[]}//通过客户模块新建日程，并自动带出相关客户,[{'id':'','name':''}]
                                projectid={prjid}
                                description={""}//客户模块需求，支持新建时传入的'基本信息-内容'
                            />)
                        }
                    </WeaNewScroll>
                </WeaRightMenu>
            </WeaDialog>
        )
    }
    getBottomButtons(){
        const {contentStore,dellCallBack,from='mymanagerproject'} = this.props;
        const {handleDialog,rightMenu,prjid} = contentStore;
        let btnArr = []; 
        rightMenu && rightMenu.length>0  && rightMenu.map(m=>{
            m.isTop == '1' && btnArr.length < 4 && btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mkzg0d@${m.type}`} type="primary" 
                    onClick={()=>{
                        if(m.type == "BTN_SAVE"){ //保存
                            this.savePrjInfo();
                         }else if(m.type == "BTN_EDIT"){//编辑
                            contentStore.getPrjInfo({viewtype:'edit'});
                         }else if(m.type == "BTN_BACK"){ //返回
                            contentStore.getPrjInfo({viewtype:'view'});
                        }else if(m.type == "BTN_DELETE"){ //删除
                            contentStore.delPrjInfo({method:"del",prjid:prjid,from:from,callBack:dellCallBack});
                        }
                    }}>
                    {m.menuName}
                </Button>
            );
        });
        btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0ki525@close`}  type="primary" onClick={()=>{handleDialog(false)}}>{getLabel(309,"关闭")}</Button>)  
        return btnArr;
    }
    getRightMenu(){
        const {contentStore} = this.props;
        const {rightMenu,isApprove} = contentStore;
        let btnArr = []; 
        rightMenu && rightMenu.length>0 && rightMenu.map(m=>{
            let disabled = false;
            if(isApprove){
                if(m.menuIcon == "icon-coms-Approval"){
                    disabled = true;
                }
            }
            btnArr.push({
                icon: <i className={m.menuIcon} />,
                content: m.menuName,
                disabled: disabled
            })
        });
    	return btnArr
    }
    onRightMenuClick(key){
        const {contentStore} = this.props;
        const {handleDialog,rightMenu,prjid} = contentStore;
        let that = this;
        rightMenu &&  rightMenu.length>0  && rightMenu.map((m,i)=>{
        	if(Number(key) == i){
                let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
                if(fn != ""){
                    fn = fn.substring(0, fn.indexOf('('));
                    if('onNormal' == fn){   //正常
                        contentStore.doPlanOpt({method:'normal',prjid:prjid});
                    }else if('onOver' == fn){   //延期
                        contentStore.doPlanOpt({method:'delay',prjid:prjid});
                    }else if('onFinish' == fn){   //完成
                        contentStore.doPlanOpt({method:'complete',prjid:prjid});            
                    }else if('onFrozen' == fn){   //冻结
                        contentStore.doPlanOpt({method:'freeze',prjid:prjid});                            
                    }else if ('onToggleStatus' == fn) {
                        contentStore.doPlanOpt({ method: 'togglestatus', prjid: prjid, statusid: m.params });
                    }
                }else{
                    if(m.type == "BTN_EDIT"){ //编辑
                        contentStore.getPrjInfo({viewtype:'edit'});
                    }else if(m.type == "BTN_SAVE"){  //保存
                        this.savePrjInfo();
                    }else if(m.type == "BTN_DELETE"){  //删除
                        contentStore.delPrjInfo({method:"del",prjid:prjid,from:"mymanagerproject"});
                    }else if(m.type == "BTN_NEWREQ"){  //新建流程
                        window.open("/spa/workflow/static/index.html#/main/workflow/add?prjid=" + prjid, "_blank");
                    }else if(m.type == "BTN_NEWDOC"){  //新建文档
                        window.open("/spa/document/static/index.html#/main/document/add?moudleFrom=prj&prjid=" + prjid, "_blank");
                    }else if(m.type == "BTN_NEWRQ"){  //新建日程
                        this.setState({ workPlanVisible: true })
                    }else if(m.type == "BTN_NEWMT"){  //新建会议
                        window.open("/spa/meeting/static/index.html#/main/meeting/dialogsingle?type=create&projectid=" + prjid, "_blank");
                    }else if(m.type == "BTN_LOG"){  //日志
                        this.refs.projectLogDialog.setVisible(true);
                        contentStore.getPrjLogList({ prjid: prjid });
                    }else if(m.type == "BTN_SAVETEMPLET"){  //另存为模板
                        contentStore.setVisiable(true);
                    }else if(m.type == "BTN_BACK"){ //返回
                        contentStore.getPrjInfo({viewtype:'view'});
                    }
                } 
            }
        });
    }

    savePrjInfo=(params={})=>{
        const {callBack} = this.props;
        const {handleDialog,prjForm,prjid,baseParams,validateRules,getPrjInfo} = this.props.contentStore;
        prjForm.validateForm().then(f=>{
            if(f.isValid){
               	let newParams = {...toJS(prjForm.getFormParams()),method:"edit",prjid:prjid,...params};
                Prj_Apis.savePrjInfo(newParams).then(data=>{
                    if(data.success){
                        getPrjInfo({viewtype:"view"});
                        if(callBack){
                            callBack();
                        }else{
                            window._table.reLoad();
                        }
                    }else{
                        message.error(data.msg);
                    }
                })
            }else{
                f.showErrors();
            }
        });
    }

    setWorkPlanVisible = (bool) => {
        this.setState({ workPlanVisible: bool })
    }

}
